package com.example.monitor.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import redis.clients.jedis.JedisPool;

import com.example.monitor.util.redis.RedisPoolMap;

/**
 * @author wangkai 自定义监听
 */
@WebListener
public class MyContextListener implements ServletContextListener {
	private Logger logger = LoggerFactory.getLogger(MyContextListener.class);

	private JedisPool jedisPool;

	@Value("${redis.host}")
	private String host;

	@Value("${redis.port}")
	private int port;
	@Value("${redis.password}")
	private String password;

	@Value("${redis.timeOut}")
	private int timeOut;

	@Value("${redis.maxActive}")
	private int maxActive;

	@Value("${redis.maxIdle}")
	private int maxIdle;

	@Value("${redis.maxWait}")
	private int maxWait;

	@Value("${redis.testOnBorrow}")
	private boolean testOnBorrow;

	@Value("${redis.testOnReturn}")
	private boolean testOnReturn;

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		// 创建redis连接池
		GenericObjectPoolConfig config = new GenericObjectPoolConfig();
		config.setMaxTotal(maxActive);
		config.setMaxIdle(maxIdle);
		config.setMaxWaitMillis(maxWait);
		config.setTestOnBorrow(testOnBorrow);
		config.setTestOnReturn(testOnReturn);
		if (jedisPool == null) {
			jedisPool = new JedisPool(config, host, port, timeOut, password);
		}
		RedisPoolMap.init().setJedisPool(jedisPool);
		logger.info("jedispool已注入");
	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		if (jedisPool != null) {
			jedisPool.close();
			jedisPool = null;
			logger.info("jedispool已销毁");
		}
	}

}
